package indi.zjh.dp.orm;

import java.sql.SQLException;
import java.util.Iterator;
import java.util.List;
import java.util.Map;

import org.apache.log4j.Logger;
import org.dom4j.DocumentException;

import indi.zjh.dp.cache.ObjectCache;
import indi.zjh.dp.db.Configuration;
import indi.zjh.dp.db.Session;
import indi.zjh.dp.util.RedisUtil;
import indi.zjh.dp.util.SerializeUtil;
import redis.clients.jedis.Jedis;

public class Search {
	private static Logger logger = Logger.getLogger(Search.class);
	
	public static Result find(Class<?> cls, Condition cond) throws SQLException, DocumentException, Exception
	{
		long stime = System.currentTimeMillis();
		Result result = ObjectCache.getInstance().getSearchResult(cond);
		
		if(result == null)
		{
			result = new Result();
			System.out.println("hashcode="+cond.hashCode());
			Session session = Configuration.getSessionFactory().createSession();
			System.out.println(cls.getName());
			RelationClass rc = Configuration.getInstance().getVersion().getRelationClass(cls.getName());
			String tableName = BusinessMapDataStrategy.getTableName(rc);
			List<Map<String, Object>> ret = session.query("SELECT `_id` FROM "+tableName);
			Iterator<Map<String, Object>> iter = ret.iterator();
			while(iter.hasNext())
			{
				Map<String, Object> row = iter.next();
				//Business obj = (Business)cls.newInstance();
				//obj.setId((Long)row.get("_id"));
				//session.get(obj);
				
				Business obj = session.getById(cls, (Long)row.get("_id"));
				if(cond.test(obj))
					result.addObject(obj);
			}
			ObjectCache.getInstance().setSearchResult(cond, result);
			session.close();
		}
		long consume = System.currentTimeMillis() - stime;
		logger.info("Search consume "+consume+" 毫秒");
		return result;
	}
}
